<?php

namespace App\Handlers;


use App\Models\Config\Channels;
use App\Models\Config\Games;
use App\Repositories\Config\ChannelsRepository;
use App\Repositories\Config\GamesRepository;
use App\Services\Config\ChannelsService;
use App\Services\Config\GamesService;
use Cache;

class GameChannelHelper
{

    protected static $cache_key = 'games_channels_info';

    public static function getGameName($gameId)
    {
        $gamesChannelsInfo = [];

        if (Cache::has(self::$cache_key)) {
            $gamesChannelsInfo = Cache::get(self::$cache_key);
        } else {
            $gamesChannelsInfo = self::genCacheInfo();
        }

        return isset($gamesChannelsInfo[$gameId]['game_name']) ? $gamesChannelsInfo[$gameId]['game_name'] : $gameId;
    }

    public static function getChannelName($gameId, $channelId)
    {
        $gamesChannelsInfo = [];

        if (Cache::has(self::$cache_key)) {
            $gamesChannelsInfo = Cache::get(self::$cache_key);
        } else {
            $gamesChannelsInfo = self::genCacheInfo();
        }

        return isset($gamesChannelsInfo[$gameId][$channelId]) ? $gamesChannelsInfo[$gameId][$channelId] : $channelId;
    }

    /**
     * 生成游戏渠道信息的缓存
     */
    private static function genCacheInfo()
    {
        $gamesChannels = [];

        $games = new Games();
        $gamesRepository = new GamesRepository($games);
        $gamesService = new GamesService($gamesRepository);
        $games = $gamesService->getGames();

        $channels = new Channels();
        $channelsRepository = new ChannelsRepository($channels);
        $channelsService = new ChannelsService($channelsRepository);
        $channels = $channelsService->getChannels();


        foreach ($games as $game) {
            $gamesChannels[$game['game_id']] = ['game_name' => $game['game_name']];
        }

        foreach ($channels as $channel) {
            $gamesChannels[$channel['game_id']][$channel['channel_id']] = $channel['channel_name'];
        }

        Cache::put(self::$cache_key, $gamesChannels, env('CACHE_EXPIRE_TIME', 10));

        return $gamesChannels;
    }
}